package com.michael.ims.gateway.config;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.michael.common.ex.BusinessException;
import com.michael.common.utils.SecurityUtil;
import com.michael.common.utils.TokenProcessor;
import com.michael.ims.gateway.component.CustomerErrorWebExceptionHandler;
import com.michael.io.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;

@Configuration
public class SystemConfig {

    public static String CONTEXT_PATH = "/ims/api";
    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    @Value("${com.michael.domain.ims-app}")
    private String imsAppDomain;

    //修改登陆返回的返回体
    private RewriteFunction<JSONObject, JSONObject> modifyResponse = ((serverWebExchange, jsonObject) -> {
        if (StringUtils.equals(jsonObject.getString("status"), "success")) {
            //封装为jwt对象
            JSONObject data = new JSONObject();
            UserInfo userInfo = jsonObject.getObject("body", UserInfo.class);

            String token = TokenProcessor.encode(2, userInfo);
            //将其token进行加密
            data.put("token", token);
            jsonObject.replace("body", data);
        }
        return Mono.just(jsonObject);
    });
    //修改请求体，往里面添加用户信息对象
    private RewriteFunction<JSONObject, JSONObject> modifyRequest = ((serverWebExchange, jsonObject) -> {
        HttpMethod method = serverWebExchange.getRequest().getMethod();
        if (HttpMethod.POST.equals(method)) {
            UserInfo userInfo = serverWebExchange.getAttribute("userInfo");
            jsonObject.put("user", userInfo);
        }
        return Mono.just(jsonObject);
    });

    public SystemConfig(ServerProperties serverProperties,
                        ResourceProperties resourceProperties,
                        ObjectProvider<List<ViewResolver>> viewResolversProvider,
                        ServerCodecConfigurer serverCodecConfigurer,
                        ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider
                .getIfAvailable(() -> Collections.emptyList());
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    public ErrorWebExceptionHandler errorWebExceptionHandler(
            ErrorAttributes errorAttributes) {
        CustomerErrorWebExceptionHandler exceptionHandler = new CustomerErrorWebExceptionHandler(
                errorAttributes, this.resourceProperties, this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("login", r ->
                        r.path(CONTEXT_PATH + "/login")
                                .filters(f -> f.rewritePath(CONTEXT_PATH + "/login", "/ims-app/user/login")
                                        .modifyResponseBody(JSONObject.class, JSONObject.class, modifyResponse))
                                .uri(imsAppDomain)
                )
                .route("ims-app", r ->
                        r.path(CONTEXT_PATH + "/ims-app/**")
                                .filters(f -> f.rewritePath(CONTEXT_PATH + "/ims-app/(?<segment>.*)", "/ims-app/${segment}")
                                        .modifyRequestBody(JSONObject.class, JSONObject.class, modifyRequest))
                                .uri(imsAppDomain)
                )
                .build();
    }
}
